package com.doumuxie.controller.base;

import com.doumuxie.service.UserService;
import com.doumuxie.util.ResultUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author doumuxie https://gitee.com/doumuxie/
 * @version 1.0
 * @date 2020/10/23 15:01
 * @description base
 **/
@Component
public class BaseController {

    @Resource
    private UserService userService;


    /**
     * 从jwt获取用户信息
     *
     * @param request 请求
     * @return jwt user dto
     */
    public Map getUser(HttpServletRequest request) {
        // 获取token
        String token = request.getHeader("token");
        // 判断token是否过期
        ResultUtil res = userService.userInfo(token);
        if (res.getSuccess()) {
            return (Map) res.getData();
        }
        return null;
    }

    /**
     * 从请求头获取token
     *
     * @param request 请求
     * @return jwt token
     */
    public String getToken(HttpServletRequest request) {
        // 获取token
        return request.getHeader("token");
    }


    /**
     * 获取请求的用户id
     *
     * @param request 请求
     * @return user id
     */
    public String getUserId(HttpServletRequest request) {
        Map<String, String> user = getUser(request);
        if (user == null) {
            return null;
        }
        return user.get("id");
    }
}
